
#include "../../Command.h"

#include "../../User.h"
#include "../../NLogic/Space.h"
#include "../../NLogic/Party.h"
#include "../../NLogic/Battle.h"



namespace ProjectZ { namespace NCommand {

void SendPacket_CS_PVP_TIME_OVER(User * pUser, int winner, int loser)
{
	pUser->GetSpace()->GetData()._winnerGID	= winner;

	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << winner;	// 승자
	*pAck << loser;	// 패자

	pAck->MakePacket(CMD_SN_FIGHT_END);
	pUser->GetSpace()->SendAll(pAck);
}

void Command::CS_PVP_TIME_OVER(User * pUser, ::Network::Packet *pPacket)
{
	PREPARE_PACKET;

	NLogic::Space * pSpace	= pUser->GetSpace();

	if (pSpace == NULL)
	{
		DEBUGLOG("CS_PVP_TIME_OVER : pSpace is NULL!!");
		return;
	}

	NLogic::Party * pParty = pSpace->GetParty();
	if (NULL == pParty)
	{
		DEBUGLOG("CS_PVP_TIME_OVER : pParty is NULL!!");
		return;
	}

	pParty->SetState(NLogic::Party::State::PVP_BATTLE_END);

	User * pOppUser = pUser->GetBattle()->GetData()._pvpOppUser;
	if (NULL == pOppUser)
	{
		DEBUGLOG("CS_PVP_TIME_OVER : pOppUser is NULL!");
		return;
	}

	int myHP	= (pUser->GetBattle()->GetData().HP / static_cast<double>(pUser->GetBattle()->GetData().HP_MAX)) * 100;
	int oppHP	= (pOppUser->GetBattle()->GetData().HP / static_cast<double>(pOppUser->GetBattle()->GetData().HP_MAX)) * 100;

	int myLevel		= pUser->GetCharacterInfo().level;
	int oppLevel	= pOppUser->GetCharacterInfo().level;

	int winnerSeq	= 0;
	int loserSeq	= 0;

	// 남은 HP의 비율이 높은 유저가 승자
	if (myHP > oppHP)
	{
		winnerSeq	= pUser->GetUserSeq();
		loserSeq	= pOppUser->GetUserSeq();
		SendPacket_CS_PVP_TIME_OVER(pUser, winnerSeq, loserSeq);
		return;
	}

	if (myHP < oppHP)
	{
		winnerSeq	= pOppUser->GetUserSeq();
		loserSeq	= pUser->GetUserSeq();
		SendPacket_CS_PVP_TIME_OVER(pUser, winnerSeq, loserSeq);
		return;
	}

	// HP가 같다면, 레벨이 낮은 유저가 승자
	if (myLevel > oppLevel)
	{
		winnerSeq	= pOppUser->GetUserSeq();
		loserSeq	= pUser->GetUserSeq();
		SendPacket_CS_PVP_TIME_OVER(pUser, winnerSeq, loserSeq);
		return;
	}

	if (myLevel < oppLevel)
	{
		winnerSeq	= pUser->GetUserSeq();
		loserSeq	= pOppUser->GetUserSeq();
		SendPacket_CS_PVP_TIME_OVER(pUser, winnerSeq, loserSeq);
		return;
	}

	// HP도 같고, 레벨도 같다면 방장이 승자
	winnerSeq	= pUser->GetUserSeq();
	loserSeq	= pOppUser->GetUserSeq();
	SendPacket_CS_PVP_TIME_OVER(pUser, winnerSeq, loserSeq);
}


} /*NCommand*/ } /*ProjectZ*/
